﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Model;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.WeChat.Service.Enums;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Options;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;

namespace CoreCms.Net.Web.WebApi.Controllers
{
    /// <summary>
    /// 微信公众号通用接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WeChatOffiaccountController : ControllerBase
    {
        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
        private readonly WeChatOptions _weChatOptions;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="weChatOptions"></param>
        /// <param name="weChatApiHttpClientFactory"></param>
        public WeChatOffiaccountController(IOptions<WeChatOptions> weChatOptions, IWeChatApiHttpClientFactory weChatApiHttpClientFactory)
        {
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            _weChatOptions = weChatOptions.Value;
        }


        /// <summary>
        /// JS-SDK使用权限签名算法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //[Authorize]
        public IActionResult GetWeChatConfig(FMGetWeChatConfig entity)
        {
            //获取全局缓存的jsapi_ticket
            var jsApiTicket = WeChatCacheAccessTokenHelper.GetWeChatJsApiTicket();
            var nonceStr = CoreCms.Net.Utility.Helper.CommonHelper.GetSerialNumber();
            var timestamp = CoreCms.Net.Utility.Helper.CommonHelper.GetTimeStampByTotalSeconds().ToString();
            //var url = Request.GetTypedHeaders().Referer;
            //获取前面
            var signatureStr = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + entity.url;
            var signature = CoreCms.Net.Utility.Helper.CommonHelper.Sha1Signature(signatureStr);

            return new JsonResult(new
            {
                jsApiTicket,
                appId = _weChatOptions.WeiXinAppId,
                timestamp,
                nonceStr,
                signature,
                entity.url,
                entity
            });
        }

        /// <summary>
        /// 通用发送模板消息方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Send(TmpMsgModel model)
        {
            try
            {
                var client = _weChatApiHttpClientFactory.CreateWeXinClient();
                var accessToken = WeChatCacheAccessTokenHelper.GetWeChatAccessToken();
                var request = new CgibinMessageTemplateSendRequest
                {
                    AccessToken = accessToken,
                    ToUserOpenId = model.OpenId,
                    TemplateId = model.TemplateId,
                    MiniProgram = null,
                    Data = new ConcurrentDictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>()
                };

                if (!string.IsNullOrEmpty(model.Url))
                {
                    request.Url = model.Url;
                }

                const string color = "#CCC";

                if (!string.IsNullOrEmpty(model.First))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("first", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.First }));
                }
                if (!string.IsNullOrEmpty(model.Keyword1))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword1 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword2))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword2 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword3))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword3", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword3 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword4))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword4", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword4 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword5))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword5", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword5 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword6))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword6", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword6 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword7))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword7", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword7 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword8))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword8", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword8 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword9))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword9", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword9 }));
                }
                if (!string.IsNullOrEmpty(model.Keyword10))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("keyword10", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Keyword10 }));
                }
                if (!string.IsNullOrEmpty(model.Remark))
                {
                    request.Data.Add(new KeyValuePair<string, CgibinMessageTemplateSendRequest.Types.DataItem>("remark", new CgibinMessageTemplateSendRequest.Types.DataItem() { Color = color, Value = model.Remark }));
                }

                var response = await client.ExecuteCgibinMessageTemplateSendAsync(request, HttpContext.RequestAborted);
                return response.ErrorCode != (int)WeChatReturnCode.ReturnCode.请求成功
                    ? new JsonResult(new { ResultCode = "1", Msg = "错误：" + response.ErrorMessage })
                    : new JsonResult(new { ResultCode = "0", Msg = "已发送成功", Data = response.MessageId });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { ResultCode = "1", Msg = ex.ToString() });
            }
        }


    }
}
